# -*- coding: utf-8 -*-

from odoo import models, fields, api
import uuid, oss2, base64, chardet
from odoo.exceptions import UserError
import chardet

class Image(models.Model):
    _name = 'image'
    _description = u'图片'

    url = fields.Char(required=True, string=u'图片')

    def upload_image_to_oss(self, data):
        '''上传图片至oss服务器 返回图片url'''
        data = base64.b64decode(data)
        name = str(uuid.uuid1())
        oss_key = self.env['ir.config_parameter'].get_param('image_oss_key')
        oss_sec = self.env['ir.config_parameter'].get_param('image_oss_sec')
        oss_internal_url = self.env['ir.config_parameter'].get_param('image_oss_internal_url')
        oss_bucket = self.env['ir.config_parameter'].get_param('image_oss_bucket')
        oss_url = self.env['ir.config_parameter'].get_param('image_oss_url')
        url = oss_url + name
        try:
            auth = oss2.Auth(oss_key, oss_sec)
            bucket = oss2.Bucket(auth, oss_internal_url, oss_bucket, connect_timeout=3)
            bucket.put_object('item/' + name, data)
        except Exception, e:
            raise UserError(u'图片上传失败！')
        return url

    def return_image_b64_data(self):
        '''下载图片 编码为base64 返回'''
        data = []
        for img in self:
            oss_key = self.env['ir.config_parameter'].get_param('image_oss_key')
            oss_sec = self.env['ir.config_parameter'].get_param('image_oss_sec')
            oss_internal_url = self.env['ir.config_parameter'].get_param('image_oss_internal_url')
            oss_bucket = self.env['ir.config_parameter'].get_param('image_oss_bucket')
            oss_url = self.env['ir.config_parameter'].get_param('image_oss_url')
            oss_url = oss_url.replace('item/', '')
            file_name = img.url.replace(oss_url, '')
            try:
                auth = oss2.Auth(oss_key, oss_sec)
                bucket = oss2.Bucket(auth, oss_internal_url, oss_bucket, connect_timeout=3)
                remote_stream = bucket.get_object(file_name)
                img_b64 = base64.b64encode(remote_stream.read())
                img_b64 = 'base64/jpg:' + img_b64
                data.append(img_b64)
            except Exception, e:
                raise UserError(u'下载图片失败！')
        return data

    def test(self):
        self.env['plan'].browse(31).get_print_plan_data()
